﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Smart.Model
{
    [System.Serializable]
    public class EndPointInfo
    {
        public ServerType eServerType;
        public string ipandport;
    }
    public class GameEntry : MonoBehaviour
    {
        [SerializeField]
        protected EndPointInfo[] mEndPoints = new EndPointInfo[0];

        NetOutComponent mNet;
        public static GameEntry Instance { get; private set; }
        public static ActorManager ActorMgr { get; private set; }
        public static RaceLogic RaceMgr { get; private set; }
        public static TimeManager TimeManager { get; private set; }

        public void Send(int msgId,Google.Protobuf.IMessage message)
        {
            if(null != mNet)
            {
                mNet.Send(ServerType.ST_LOGIC, msgId, message);
            }
        }

        public T Clone<T>(string templateName,System.Action<T> onCreate)where T:MonoBehaviour
        {
            var go = GameObject.Find($"Template");
            if(null != go)
            {
                var child = go.transform.Find(templateName);
                if(null != child)
                {
                    T obj = Object.Instantiate(child.gameObject).GetComponent<T>();
                    if(null != onCreate && null != obj)
                    {
                        onCreate(obj);
                    }
                    return obj;
                }
            }
            return null;
        }

        private void Awake()
        {
            Instance = this;
            DontDestroyOnLoad(this.gameObject);
            this.gameObject.AddComponent<CppLog>();
            ActorMgr = new GameObject("ActorManager").AddComponent<ActorManager>();
            DontDestroyOnLoad(ActorMgr.gameObject);
            TimeManager = new GameObject("TimeManager").AddComponent<TimeManager>();
            DontDestroyOnLoad(TimeManager.gameObject);

            RaceMgr = Clone<RaceLogic>("Race", f =>
            {
                f.gameObject.SetActive(true);
            });

            Net.Init();

            this.gameObject.AddComponent<NetMessageQueue>();
            mNet = this.gameObject.AddComponent<NetOutComponent>();

            for (int i = 0; i < mEndPoints.Length;++i)
            {
                var endpoint = mEndPoints[i];
                mNet.Connect(endpoint.eServerType,endpoint.ipandport);
            }
        }

        private void Start()
        {
            Net.LoginReqMessage();
        }

        void HandleNetDisconnect()
        {

        }

        private void OnDestroy()
        {
            Net.Clear();
        }
    }
}